<template>
  <!--养殖信息-->
<div style="margin-top: 15px;">
  <table style="width: 100%;">
        <thead></thead>
        <tbody>
          <tr>
            <td style="color:dodgerblue;font-size: 20px;">养殖信息
              &nbsp;&nbsp;&nbsp;&nbsp;
              <el-button type="info" @click="SetUp">设置</el-button>
            </td>
          </tr>

          <tr>
            <td>品种：{{ breedData.quality }}</td>
            <td>来源：{{ breedData.source }}</td>
          </tr>

          <tr>
            <td>饲养天数：{{ breedData.feedingDays }}天</td>
            <td>饲养品牌：{{ breedData.feedBrand }}</td>
          </tr>

          <tr>
            <td>饲养负责人：{{ breedData.breedingManager }}</td>
            <td>出栏日期：{{ breedData.dateOfSlaughter }}</td>
          </tr>
        </tbody>
      </table>
</div>

<!--疫苗信息-->
<div style="margin-top: 30px;">
<table>
  <thead></thead>
  <tbody>
    <tr>
      <td style="color:dodgerblue;font-size: 20px;">免疫信息
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="info" @click="addDomain">新增行</el-button>
      </td>
    </tr>

    <tr style="background-color:darkgrey;">
      <td>饲养天数</td>
      <td>免疫方式</td>
      <td>免疫方法</td>
      <td>操作</td>
    </tr>

    <tr v-for="item in TraceabilitiesData" :key="item.traceabilityId">
      <td>{{ item.feedingDays }}</td>
      <td>{{ item.immuneSystem }}</td>
      <td>{{ item.immuneMethods }}</td>
      <td>
        <el-link type="primary" @click="UpdateTraceabilities">修改</el-link>&nbsp;
        <el-link type="primary" @click="DelTraceabilities(item.traceabilityId)">删除</el-link>
      </td>
    </tr>

    <tr>
      <td>  
        <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key"  :prop="'domains.' + index + '.value'" >
            <el-input v-model="TraceabilitiesForm.feedingDays" style="width: 180px;" />
          </el-form-item>
      </td>

      <td>  
        <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key"  :prop="'domains.' + index + '.value'" >
            <el-input v-model="TraceabilitiesForm.immuneSystem" style="width: 180px;" />
          </el-form-item>
      </td>

      <td>  
        <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key" :prop="'domains.' + index + '.value'" >
            <el-input v-model="TraceabilitiesForm.immuneMethods" style="width: 180px;" />
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <el-link type="primary" @click="SaveTraceability">保存</el-link>&nbsp;
            <el-link type="primary" class="mt-2" @click.prevent="removeDomain(domain)">取消</el-link>
          </el-form-item>
      </td>
    </tr>

    <tr>
      <td style="color:dodgerblue;font-size: 20px;">动检证</td>
    </tr>
      <span v-for="item in TraceabilitiesData" :key="item.traceabilityId"><img :src="item.pictureName" width="100px" height="100px" />&nbsp;&nbsp;&nbsp;</span>
      <el-button style="width: 100px;height: 100px;" @click="dialogFormVisible=true">+</el-button>
  </tbody>
</table>
</div>

  <!--企业信息-->
<div style="margin-top: 15px;">
<table style="width: 30%;">
      <thead></thead>
      <tbody>
        <tr>
          <td style="color:dodgerblue;font-size: 20px;">企业信息
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button type="info" @click="dialogFormVisibleAddEnterprise=true">设置</el-button>
          </td>
        </tr>

        <tr>
          <td>养殖场：{{ EnterpriseData.livestockFarm }}</td>
          <td>负责人：{{ EnterpriseData.personInCharge }}</td>
        </tr>

        <tr>
          <td>存栏数量：{{ EnterpriseData.inventoryQuantity }}只</td>
        </tr>

        <tr>
          <td style="color:dodgerblue;font-size: 20px;">企业照片</td>
        </tr>
        
        <tr>
          <td>
            <span v-for="item in picData" :key="item.enterpriseId"><img :src="item.pictureName" width="90px" height="90px" />&nbsp;&nbsp;&nbsp;</span>
            <el-button style="width: 100px;height: 100px;" @click="dialogFormVisible=true">+</el-button>
          </td>
        </tr>
      </tbody>
    </table>
</div>

<!--表单添加养殖信息-->
<div>
  <el-dialog v-model="dialogFormVisibleAdd" title="养殖信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="breedForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

      <el-form-item label="品种" prop="quality">
      <el-input v-model="breedForm.quality" placeholder="请输入品种" />
    </el-form-item>

    <el-form-item label="来源" prop="source">
      <el-input v-model="breedForm.source" placeholder="请输入来源" />
    </el-form-item>

    <el-form-item label="饲养天数" prop="feedingDays">
      <el-input v-model="breedForm.feedingDays" placeholder="请输入饲养天数" />
    </el-form-item>

    <el-form-item label="饲养品牌" prop="feedBrand">
      <el-input v-model="breedForm.feedBrand" placeholder="请输入饲养品牌" />
    </el-form-item>

    <el-form-item label="饲养负责人" prop="breedingManager">
      <el-input v-model="breedForm.breedingManager" placeholder="请输入饲养负责人" />
    </el-form-item>

    <el-form-item label="出栏日期" prop="dateOfSlaughter">
      <el-date-picker v-model="breedForm.dateOfSlaughter" type="date" placeholder="请选择出栏日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

<!--表单修改养殖信息-->
<div>
  <el-dialog v-model="dialogFormVisibleUpdate" title="养殖信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="breedForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

    <el-form-item label="品种" prop="quality">
      <el-input v-model="breedForm.quality" placeholder="请输入品种" />
    </el-form-item>

    <el-form-item label="来源" prop="source">
      <el-input v-model="breedForm.source" placeholder="请输入来源" />
    </el-form-item>

    <el-form-item label="饲养天数" prop="feedingDays">
      <el-input v-model="breedForm.feedingDays" placeholder="请输入饲养天数" />
    </el-form-item>

    <el-form-item label="饲养品牌" prop="feedBrand">
      <el-input v-model="breedForm.feedBrand" placeholder="请输入饲养品牌" />
    </el-form-item>

    <el-form-item label="饲养负责人" prop="breedingManager">
      <el-input v-model="breedForm.breedingManager" placeholder="请输入饲养负责人" />
    </el-form-item>

    <el-form-item label="出栏日期" prop="dateOfSlaughter">
      <el-date-picker v-model="breedForm.dateOfSlaughter" type="date" placeholder="请选择出栏日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">修改</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

<!--表单添加企业信息-->
<div>
  <el-dialog v-model="dialogFormVisibleAddEnterprise" title="企业信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="enterpriseForm" :rules="enterpriseFormRules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

    <el-form-item label="养殖场" prop="livestockFarm">
      <el-input v-model="enterpriseForm.livestockFarm" placeholder="请输入养殖场名称" />
    </el-form-item>

    <el-form-item label="负责人" prop="personInCharge">
      <el-input v-model="enterpriseForm.personInCharge" placeholder="请输入负责人" />
    </el-form-item>

    <el-form-item label="存栏数量(只)" prop="inventoryQuantity">
      <el-input v-model="enterpriseForm.inventoryQuantity" placeholder="请输入存栏数量(只)" />
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="addEnterprise">保存</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

  <!--表单添加企业图片-->
  <div>
  <el-dialog v-model="dialogFormVisible" width="500" align-center>
    <el-upload class="avatar-uploader" action="http://localhost:5063/api/PictureManagement/UploadFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="form.pictureNames" :src="form.pictureNames" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</el-dialog>
</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Search, Share, Upload,Plus } from '@element-plus/icons-vue'
import {useRoute,useRouter} from 'vue-router'
import type { UploadProps } from 'element-plus'

const route = useRoute();
const router = useRouter();
//表单校验
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

onMounted(() => {
  
  saveUpdate()
  //养殖
  getBreedData()
  //免疫
  getTraceabilitiesData()

  //企业
  getEnterpriseList()
})

//商品Form
const form: any = reactive({
  shoppingId: route.query.shoppingId,
  shoppingNameId: '',
  productionBatch: '',
  qgPeriod: '',
  productionLicense: '',
  manufacturingEnterprise: '',
  pictureId: '',
  pictureName: '',
  pictureNames: '',
  createdBy: '',
  createdDate: '',
  deletedBy: '',
  deletedDate: '',
  updatedBy: '',
  updateDate: '',
  isDeleted: '',
  shoppingNames: '',
})

//养殖Form
const breedForm:any = reactive({
  breedId:'',
  quality: '',
  source: '',
  feedingDays: '',
  feedBrand: '',
  breedingManager: '',
  dateOfSlaughter: '',
  productionBatch: '',
  shoppingId: '',
  createdBy: '',
  createdDate:''
})

//疫苗信息
const TraceabilitiesForm:any = reactive({
  traceabilityId:'',
  feedingDays: '',
  immuneSystem: '',
  immuneMethods: '',
  productionBatch: '',
  shoppingId: '',
  createdBy: '',
  updateBy: '',
})

//企业信息
const enterpriseForm:any = reactive({
  livestockFarm: '',
  personInCharge: '',
  inventoryQuantity:''
})

//企业照片对话框
const dialogFormVisible = ref(false)
//养殖信息添加
const dialogFormVisibleAdd = ref(false)
//养殖信息修改
const dialogFormVisibleUpdate = ref(false)
//养殖信息添加
const dialogFormVisibleAddEnterprise = ref(false)
//图片上传
const handleAvatarSuccess = (picUrl: any) => {
  console.log(picUrl);
  
  form.pictureName = picUrl.data;
} 
//上传前判断(文件类型、文件大小)
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/gif' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式必须是[JPG,GIF,PNG]格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2MB!')
    return false
  }
  return true
}

//养殖信息校验
const rules = reactive<FormRules>({
  quality: [
    { required: true, message: '请输入品种', trigger: 'change',},
  ],
  source: [
    { required: true, message: '请输入来源', trigger: 'blur' },
  ],
  feedingDays: [
    { required: true, message: '请输入饲养天数', trigger: 'blur' },
  ],
  feedBrand: [
    { required: true, message: '请输入饲养品牌', trigger: 'blur' },
  ],
  breedingManager: [
    { required: true, message: '请输入饲养负责人', trigger: 'blur' },
  ],
  dateOfSlaughter: [
    { required: true, message: '请选择出栏日期', trigger: 'blur' },
  ],
})

//企业信息校验
const enterpriseFormRules=reactive<FormRules>({
  livestockFarm: [
    { required: true, message: '请输入养殖场名称', trigger: 'change',},
  ],
  personInCharge: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
  ],
  inventoryQuantity: [
    { required: true, message: '请输入存栏数量', trigger: 'blur' },
  ],
})

//反填商品信息
const saveUpdate = () => {
  let Backshopping = {
    shoppingId:form.shoppingId
  }
  axios.post('api/ShoppingManagement/BackInfoShopping',Backshopping).then(res => {
    console.log(res);
    let back = res.data.data;
    form.shoppingId = back.shoppingId;
    form.shoppingNameId = back.shoppingNameId;
    form.shoppingNames = back.shoppingNames;
    form.productionBatch=back.productionBatch;
    form.qgPeriod=back.qgPeriod;
    form.productionLicense=back.productionLicense;
    form.manufacturingEnterprise = back.manufacturingEnterprise;
    form.pictureId = back.pictureId;
    form.pictureName = back.pictureName;   
    form.createdBy = back.createdBy;
    form.createdDate = back.createdDate;
    form.deletedBy = back.deletedBy;
    form.deletedDate = back.deletedDate;
    form.updatedBy = localStorage.userName;
    form.updateDate=Date.now;
    form.isDeleted=back.isDeleted
  }).catch(err => {
    console.log(err);

  })
}

//养殖信息设置
const SetUp = () => {
  if (breedForm.breedId == "") {
    //打开养殖添加对话框
    dialogFormVisibleAdd.value=true
    //添加养殖信息
  } else {
    //打开养殖修改对话框
    dialogFormVisibleUpdate.value = true
    //反填信息
    BackBreedData()
    //修改养殖信息
  }
}

//添加养殖信息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let breed = {
        quality: breedForm.quality,
        source: breedForm.source,
        feedingDays: breedForm.feedingDays,
        feedBrand: breedForm.feedBrand,
        breedingManager: breedForm.breedingManager,
        dateOfSlaughter: breedForm.dateOfSlaughter,
        productionBatch: form.productionBatch,
        shoppingId: route.query.shoppingId,
        createdBy: localStorage.userName,
        createDate: Date.now
      }
      axios.post('/api/BreedManagement/AddBreedInfo',breed).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("保存成功!")
          //关闭对话框
          dialogFormVisibleAdd.value = false;
        } 
        if (res.data.code == -1) {
          ElMessage.error("保存失败!")
          return
        }
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//显示养殖信息
const breedData:any=ref([])
const getBreedData = () => {
  let breed = {
    shoppingId:route.query.shoppingId
  }
  axios.post('/api/BreedManagement/ShowBreedList',breed).then(res=>{
    console.log(res);
    breedData.value = res.data.data[0];
    breedForm.breedId = res.data.data[0].breedId;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//反填养殖信息
const BackBreedData = () => {
  let breed = {
    breedId:breedForm.breedId
  }
  axios.post('/api/BreedManagement/BackInfoBreed',breed).then(res=>{
    console.log(res);
    let BackbreedData = res.data.data;
    breedForm.breedId = BackbreedData.breedId;
    breedForm.quality = BackbreedData.quality;
    breedForm.source = BackbreedData.source;
    breedForm.feedingDays = BackbreedData.feedingDays;
    breedForm.feedBrand = BackbreedData.feedBrand;
    breedForm.breedingManager=BackbreedData.breedingManager
    breedForm.dateOfSlaughter=BackbreedData.dateOfSlaughter
    form.productionBatch = BackbreedData.productionBatch;
  }).catch(err=>{
    console.log(err);
    
  })    
}


//修改养殖信息
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let UpdateBreed = {
        breedId: breedForm.breedId,
        shoppingId:route.query.shoppingId,
        quality: breedForm.quality,
        source: breedForm.source,
        feedingDays: breedForm.feedingDays,
        feedBrand: breedForm.feedBrand,
        breedingManager: breedForm.breedingManager,
        dateOfSlaughter: breedForm.dateOfSlaughter,
        productionBatch: form.productionBatch,
        updateBy: localStorage.userName,
      }
      axios.post('/api/BreedManagement/UpdateBreed',UpdateBreed).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("修改成功!")
          //关闭对话框
          dialogFormVisibleUpdate.value = false
          //刷新养殖信息页面
          getBreedData()
        } 
        if (res.data.code == -1) {
          ElMessage.error("修改失败!")
          return
        }
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//免疫
//显示免疫信息
const TraceabilitiesData:any=ref([])
const getTraceabilitiesData = () => {
  let TraceabilitiesInfo = {
    shoppingId:route.query.shoppingId
  }
  axios.post('/api/TraceabilitiesManagement/ShowBreedList',TraceabilitiesInfo).then(res=>{
    console.log(res);
    TraceabilitiesData.value = res.data.data;
  }).catch(err=>{
    console.log(err);
    
  })    
}

const dynamicValidateForm = reactive<{ domains: DomainItem[]}>({
  domains: [
    {
      key: 1,
      value: '',
    },
  ],
})

interface DomainItem {
  key: number
  value: string
}

//删除空白输入行
const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1)
  }
}

//新增行
const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    value: '',
  })
}

//保存
const SaveTraceability = () => {
  let traceabilities = {
        feedingDays: TraceabilitiesForm.feedingDays,
        immuneSystem: TraceabilitiesForm.immuneSystem,
        immuneMethods: TraceabilitiesForm.immuneMethods,
        productionBatch: form.productionBatch,
        shoppingId: route.query.shoppingId,
        createdBy: localStorage.userName,
      }
      axios.post('/api/TraceabilitiesManagement/AdTraceabilitiesInfo',traceabilities).then(res => {
        console.log(res);
        if (res.data.code > 0) {
          ElMessage.success("保存成功!")
          //刷新局部信息
          getTraceabilitiesData()
          //清空输入框数据
          TraceabilitiesForm.feedingDays = "";
          TraceabilitiesForm.immuneSystem = "";
          TraceabilitiesForm.immuneMethods = "";
        } else {
          ElMessage.error("报错失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
}

//删除免疫信息
const DelTraceabilities = (traceabilityId:number) => {
  let delTraceabilities = {
    traceabilityId: traceabilityId,
    userName:localStorage.userName
  }
  ElMessageBox.confirm(
    '确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      axios.post('/api/TraceabilitiesManagement/DeletedTraceabilities', delTraceabilities).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("删除成功!");
          //刷新页面
          getTraceabilitiesData()
        } else {
          ElMessage.error("删除失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//修改免疫信息
const UpdateTraceabilities = () => {
  let updateTraceabilities = {
    traceabilityId: TraceabilitiesForm.traceabilityId,
    feedingDays: TraceabilitiesForm.feedingDays,
    immuneSystem: TraceabilitiesForm.immuneSystem,
    immuneMethods: TraceabilitiesForm.immuneMethods,
    productionBatch: form.productionBatch,
    shoppingId: route.query.shoppingId,
    updateBy: localStorage.userName,
  }
  axios.post('/api/TraceabilitiesManagement/UpdateTraceabilities', updateTraceabilities).then(res => {
    console.log(res);
    if (res.data.code == 0) {
      ElMessage.success("修改成功!")
      //刷新页面
      getTraceabilitiesData()
    } else {
      ElMessage.error("修改失败!")
      return
    }
  }).catch(err => {
    console.log(err);

  })
}


//企业
//添加养殖企业信息
const addEnterprise = () => {
  //打开对话框
  dialogFormVisibleAddEnterprise.value = true;
  let enterprise:any = {
    livestockFarm: enterpriseForm.livestockFarm,
    personInCharge: enterpriseForm.personInCharge,
    inventoryQuantity: enterpriseForm.inventoryQuantity,
    shoppingId: route.query.shoppingId,
    createdBy: localStorage.userName,
  }
  axios.post('/api/EnterpriseManagement/AddBreedEnterpriseInfo',enterprise).then(res => {
    console.log(res);
    if (res.data.code == 1) {
      ElMessage.success("保存成功!")
      //关闭对话框
      dialogFormVisibleAddEnterprise.value = false;
      //刷新企业信息页面
      getEnterpriseList()
    }
    if (res.data.code == -1) {
      ElMessage.error("保存失败!")
      return
    }
  }).catch(err => {
    console.log(err);

  })
}

//查询企业信息
const EnterpriseData: any = ref([])
//图片
const picData:any=ref([])
const getEnterpriseList = () => {
  axios.post('/api/EnterpriseManagement/SearchEnterprise',{}).then(res => {
    console.log(res);
    EnterpriseData.value = res.data.data[0];
    picData.value=res.data.data
  }).catch(err => {
    console.log(err);

  })
}

</script>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>